<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  
  <title>Android插件化原理解析——Hook机制之动态代理 | 会飞的猪</title>
  
  

  

  <meta name="HandheldFriendly" content="True">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <!-- meta -->
  

  <!-- link -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css">
 <link rel="stylesheet" href="/live2d/css/live2d.css">
  
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.css">
  
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.6.3/css/all.min.css">
  

  
  <link rel="shortcut icon" type="image/x-icon" href="https://cdn.jsdelivr.net/gh/xaoxuu/assets@master/favicon/favicon.ico">
  

  
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-material-x@19.5/css/style.css">
  

  <script>
    function setLoadingBarProgress(num) {
      document.getElementById('loading-bar').style.width=num+"%";
    }
  </script>

  
  
</head>



<body>
<script src="https://g.joyinshare.com/hc/piao.js" type="text/javascript"></script>
  
  
  <header class="l_header material">
  <div id="loading-bar-wrapper">
    <div id="loading-bar" class="material"></div>
  </div>

	<div class='wrapper'>
		<div class="nav-main container container--flex">
      <a class="logo flat-box" href='/' >
        
          会飞的猪
        
      </a>
			<div class='menu navgation'>
				<ul class='h-list'>
          
  					
  						<li>
								<a class="nav flat-box" href="/"
                  
                  
                  id="home">
									<i class='fas fa-grin fa-fw'></i>&nbsp;主页
								</a>
							</li>
      			
  						<li>
								<a class="nav flat-box" href="/blog/categories/"
                  
                    rel="nofollow"
                  
                  
                  id="blogcategories">
									<i class='fas fa-folder-open fa-fw'></i>&nbsp;分类
								</a>
							</li>
      			
  						<li>
								<a class="nav flat-box" href="https://wiki.zyqing.ml"
                  
                    rel="nofollow"
                  
                  
                  id="https:wiki.zyqing.ml">
									<i class='fas fa-graduation-cap fa-fw'></i>&nbsp;技术预研
								</a>
							</li>
      			
  						<li>
								<a class="nav flat-box" href="/about/"
                  
                    rel="nofollow"
                  
                  
                  id="about">
									<i class='fas fa-user fa-fw'></i>&nbsp;关于
								</a>
							</li>
      			
  						<li>
								<a class="nav flat-box" href="/markPage/"
                  
                    rel="nofollow"
                  
                  
                  id="markPage">
									<i class='fas fa-book fa-fw'></i>&nbsp;MarkDown工具
								</a>
							</li>
      			
  						<li>
								<a class="nav flat-box" href="http://love.zyqing.ml"
                  
                    rel="nofollow"
                  
                  
                  id="http:love.zyqing.ml">
									<i class='fas fa-heart fa-fw'></i>&nbsp;爱情小屋
								</a>
							</li>
      			
      		
				</ul>
			</div>

			
				<div class="m_search">
					<form name="searchform" class="form u-search-form">
						<input type="text" class="input u-search-input" placeholder="搜索" />
						<i class="icon fas fa-search fa-fw"></i>
					</form>
				</div>
			
			<ul class='switcher h-list'>
				
					<li class='s-search'><a class="fas fa-search fa-fw" href='javascript:void(0)'></a></li>
				
				<li class='s-menu'><a class="fas fa-bars fa-fw" href='javascript:void(0)'></a></li>
			</ul>
		</div>

		<div class='nav-sub container container--flex'>
			<a class="logo flat-box"></a>
			<ul class='switcher h-list'>
				<li class='s-comment'><a class="flat-btn fas fa-comments fa-fw" href='javascript:void(0)'></a></li>
        
          <li class='s-toc'><a class="flat-btn fas fa-list fa-fw" href='javascript:void(0)'></a></li>
        
			</ul>
		</div>
	</div>
</header>
	<aside class="menu-phone">
    <header>
		<nav class="menu navgation">
      <ul>
        
          
            <li>
							<a class="nav flat-box" href="/"
                
                
                id="home">
								<i class='fas fa-clock fa-fw'></i>&nbsp;近期文章
							</a>
            </li>
          
            <li>
							<a class="nav flat-box" href="/blog/archives/"
                
                  rel="nofollow"
                
                
                id="blogarchives">
								<i class='fas fa-archive fa-fw'></i>&nbsp;文章归档
							</a>
            </li>
          
            <li>
							<a class="nav flat-box" href="/projects/"
                
                
                id="projects">
								<i class='fas fa-code-branch fa-fw'></i>&nbsp;开源项目
							</a>
            </li>
          
            <li>
							<a class="nav flat-box" href="/friends/"
                
                  rel="nofollow"
                
                
                id="friends">
								<i class='fas fa-link fa-fw'></i>&nbsp;我的友链
							</a>
            </li>
          
            <li>
							<a class="nav flat-box" href="/markPage/"
                
                  rel="nofollow"
                
                
                id="markPage">
								<i class='fas fa-book fa-fw'></i>&nbsp;MarkDown工具
							</a>
            </li>
          
            <li>
							<a class="nav flat-box" href="/2md/"
                
                  rel="nofollow"
                
                
                id="2md">
								<i class='fas fa-book fa-fw'></i>&nbsp;HTML转MD
							</a>
            </li>
          
            <li>
							<a class="nav flat-box" href="http://love.zyqing.ml"
                
                  rel="nofollow"
                
                
                id="http:love.zyqing.ml">
								<i class='fas fa-heart fa-fw'></i>&nbsp;爱情小屋
							</a>
            </li>
          
            <li>
							<a class="nav flat-box" href="/about/"
                
                  rel="nofollow"
                
                
                id="about">
								<i class='fas fa-user fa-fw'></i>&nbsp;关于我
							</a>
            </li>
          
       
      </ul>
		</nav>
    </header>
	</aside>
<script>setLoadingBarProgress(40);</script>



  <div class="l_body nocover">
    <div class='body-wrapper'>
      <div class='l_main'>
  

  
    <article id="post" class="post white-box article-type-post" itemscope itemprop="blogPost">
      


  <section class='meta'>
    
    
    <div class="meta" id="header-meta">
      
        
  
    <h1 class="title">
      <a href="/2018/01/06/data/hookAndroid1/">
        Android插件化原理解析——Hook机制之动态代理
      </a>
    </h1>
  


      
      <div class='new-meta-box'>
        
          
        
          
            
  <div class='new-meta-item author'>
    <a href="https://zyqing.ml" rel="nofollow">
      
        <i class="fas fa-user" aria-hidden="true"></i>
      
      <p>yongqing.zhu</p>
    </a>
  </div>


          
        
          
            <div class="new-meta-item date">
  <a class='notlink'>
    <i class="fas fa-calendar-alt" aria-hidden="true"></i>
    <p>2018-01-06</p>
  </a>
</div>

          
        
          
            
  
  <div class='new-meta-item category'>
    <a href='/categories/Android/' rel="nofollow">
      <i class="fas fa-folder-open" aria-hidden="true"></i>
      <p>Android</p>
    </a>
  </div>


          
        
          
            
  
    <div class="new-meta-item browse busuanzi">
      <a class='notlink'>
        <i class="fas fa-eye" aria-hidden="true"></i>
        <p>
          <span id="busuanzi_value_page_pv">
            <i class="fas fa-spinner fa-spin fa-fw" aria-hidden="true"></i>
          </span>
        </p>
      </a>
    </div>
  


          
        
          
            

          
        
      </div>
      
        <hr>
      
    </div>
  </section>


      <section class="article typo">
        <div class="article-entry" itemprop="articleBody">
          <h1 id="Android插件化"><a href="#Android插件化" class="headerlink" title="Android插件化"></a>Android插件化</h1><p>使用代理机制进行API Hook进而达到方法增强是框架的常用手段，比如J2EE框架Spring通过动态代理优雅地实现了AOP编程，极大地提升了Web开发效率；同样，插件框架也广泛使用了代理机制来增强系统API从而达到插件化的目的。本文将带你了解基于动态代理的Hook机制。</p>
<a id="more"></a>
<h2 id="代理是什么"><a href="#代理是什么" class="headerlink" title="代理是什么"></a>代理是什么</h2><p>为什么需要代理呢？其实这个代理与日常生活中的“代理”，“中介”差不多；比如你想海淘买东西，总不可能亲自飞到国外去购物吧，这时候我们使用第三方海淘服务比如惠惠购物助手等；同样拿购物为例，有时候第三方购物会有折扣比如当初的米折网，这时候我们可以少花点钱；当然有时候这个“代理”比较坑，坑我们的钱，坑我们的货。</p>
<p>从这个例子可以看出来，代理可以实现方法增强，比如常用的日志,缓存等；也可以实现方法拦截，通过代理方法修改原方法的参数和返回值，从而实现某种不可告人的目的～接下来我们用代码解释一下。</p>
<h2 id="静态代理"><a href="#静态代理" class="headerlink" title="静态代理"></a>静态代理</h2><p>静态代理，是最原始的代理方式；假设我们有一个购物的接口，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Shopping</span> </span>&#123;</span><br><span class="line">Object[] doShopping(<span class="keyword">long</span> money);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>它有一个原始的实现，我们可以理解为亲自，直接去商店购物：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ShoppingImpl</span> <span class="keyword">implements</span> <span class="title">Shopping</span> </span>&#123;</span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="keyword">public</span> Object[] doShopping(<span class="keyword">long</span> money) &#123;</span><br><span class="line">System.out.println(<span class="string">"逛淘宝 ,逛商场,买买买!!"</span>);</span><br><span class="line">System.out.println(String.format(<span class="string">"花了%s块钱"</span>, money));</span><br><span class="line"><span class="keyword">return</span> <span class="keyword">new</span> Object[] &#123; <span class="string">"鞋子"</span>, <span class="string">"衣服"</span>, <span class="string">"零食"</span> &#125;;</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>好了，现在我们自己没时间但是需要买东西，于是我们就找了个代理帮我们买：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ProxyShopping</span> <span class="keyword">implements</span> <span class="title">Shopping</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">Shopping base;</span><br><span class="line"></span><br><span class="line">ProxyShopping(Shopping base) &#123;</span><br><span class="line"><span class="keyword">this</span>.base = base;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="keyword">public</span> Object[] doShopping(<span class="keyword">long</span> money) &#123;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 先黑点钱(修改输入参数)</span></span><br><span class="line"><span class="keyword">long</span> readCost = (<span class="keyword">long</span>) (money * <span class="number">0.5</span>);</span><br><span class="line"></span><br><span class="line">System.out.println(String.format(<span class="string">"花了%s块钱"</span>, readCost));</span><br><span class="line"></span><br><span class="line"><span class="comment">// 帮忙买东西</span></span><br><span class="line">Object[] things = base.doShopping(readCost);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 偷梁换柱(修改返回值)</span></span><br><span class="line"><span class="keyword">if</span> (things != <span class="keyword">null</span> &amp;&amp; things.length &gt; <span class="number">1</span>) &#123;</span><br><span class="line">things[<span class="number">0</span>] = <span class="string">"被掉包的东西!!"</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">return</span> things;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>很不幸，我们找的这个代理有点坑，坑了我们的钱还坑了我们的货；先忍忍。</p>
<h2 id="动态代理"><a href="#动态代理" class="headerlink" title="动态代理"></a>动态代理</h2><p>传统的静态代理模式需要为每一个需要代理的类写一个代理类，如果需要代理的类有几百个那不是要累死？为了更优雅地实现代理模式，JDK提供了动态代理方式，可以简单理解为JVM可以在运行时帮我们动态生成一系列的代理类，这样我们就不需要手写每一个静态的代理类了。依然以购物为例，用动态代理实现如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">Shopping women = <span class="keyword">new</span> ShoppingImpl();</span><br><span class="line"><span class="comment">// 正常购物</span></span><br><span class="line">System.out.println(Arrays.toString(women.doShopping(<span class="number">100</span>)));</span><br><span class="line"><span class="comment">// 招代理</span></span><br><span class="line">women = (Shopping) Proxy.newProxyInstance(Shopping.class.getClassLoader(),</span><br><span class="line">women.getClass().getInterfaces(), <span class="keyword">new</span> ShoppingHandler(women));</span><br><span class="line"></span><br><span class="line">System.out.println(Arrays.toString(women.doShopping(<span class="number">100</span>)));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Android插件化原理解析——Hook机制之动态代理发表于 2016-01-28   |   139条评论   |   30448次阅读</p>
<p>使用代理机制进行API Hook进而达到方法增强是框架的常用手段，比如J2EE框架Spring通过动态代理优雅地实现了AOP编程，极大地提升了Web开发效率；同样，插件框架也广泛使用了代理机制来增强系统API从而达到插件化的目的。本文将带你了解基于动态代理的Hook机制。<br>阅读本文之前，可以先clone一份 understand-plugin-framework，参考此项目的dynamic-proxy-hook模块。另外，插件框架原理解析系列文章见索引。代理是什么<br>为什么需要代理呢？其实这个代理与日常生活中的“代理”，“中介”差不多；比如你想海淘买东西，总不可能亲自飞到国外去购物吧，这时候我们使用第三方海淘服务比如惠惠购物助手等；同样拿购物为例，有时候第三方购物会有折扣比如当初的米折网，这时候我们可以少花点钱；当然有时候这个“代理”比较坑，坑我们的钱，坑我们的货。</p>
<p>从这个例子可以看出来，代理可以实现方法增强，比如常用的日志,缓存等；也可以实现方法拦截，通过代理方法修改原方法的参数和返回值，从而实现某种不可告人的目的～接下来我们用代码解释一下。静态代理<br>静态代理，是最原始的代理方式；假设我们有一个购物的接口，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Shopping</span> </span>&#123;</span><br><span class="line">Object[] doShopping(<span class="keyword">long</span> money);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>它有一个原始的实现，我们可以理解为亲自，直接去商店购物：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ShoppingImpl</span> <span class="keyword">implements</span> <span class="title">Shopping</span> </span>&#123;</span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="keyword">public</span> Object[] doShopping(<span class="keyword">long</span> money) &#123;</span><br><span class="line">System.out.println(<span class="string">"逛淘宝 ,逛商场,买买买!!"</span>);</span><br><span class="line">System.out.println(String.format(<span class="string">"花了%s块钱"</span>, money));</span><br><span class="line"><span class="keyword">return</span> <span class="keyword">new</span> Object[] &#123; <span class="string">"鞋子"</span>, <span class="string">"衣服"</span>, <span class="string">"零食"</span> &#125;;</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>好了，现在我们自己没时间但是需要买东西，于是我们就找了个代理帮我们买：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ProxyShopping</span> <span class="keyword">implements</span> <span class="title">Shopping</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">Shopping base;</span><br><span class="line"></span><br><span class="line">ProxyShopping(Shopping base) &#123;</span><br><span class="line"><span class="keyword">this</span>.base = base;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="keyword">public</span> Object[] doShopping(<span class="keyword">long</span> money) &#123;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 先黑点钱(修改输入参数)</span></span><br><span class="line"><span class="keyword">long</span> readCost = (<span class="keyword">long</span>) (money * <span class="number">0.5</span>);</span><br><span class="line"></span><br><span class="line">System.out.println(String.format(<span class="string">"花了%s块钱"</span>, readCost));</span><br><span class="line"></span><br><span class="line"><span class="comment">// 帮忙买东西</span></span><br><span class="line">Object[] things = base.doShopping(readCost);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 偷梁换柱(修改返回值)</span></span><br><span class="line"><span class="keyword">if</span> (things != <span class="keyword">null</span> &amp;&amp; things.length &gt; <span class="number">1</span>) &#123;</span><br><span class="line">things[<span class="number">0</span>] = <span class="string">"被掉包的东西!!"</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">return</span> things;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>很不幸，我们找的这个代理有点坑，坑了我们的钱还坑了我们的货；先忍忍。动态代理<br>传统的静态代理模式需要为每一个需要代理的类写一个代理类，如果需要代理的类有几百个那不是要累死？为了更优雅地实现代理模式，JDK提供了动态代理方式，可以简单理解为JVM可以在运行时帮我们动态生成一系列的代理类，这样我们就不需要手写每一个静态的代理类了。依然以购物为例，用动态代理实现如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">Shopping women = <span class="keyword">new</span> ShoppingImpl();</span><br><span class="line"><span class="comment">// 正常购物</span></span><br><span class="line">System.out.println(Arrays.toString(women.doShopping(<span class="number">100</span>)));</span><br><span class="line"><span class="comment">// 招代理</span></span><br><span class="line">women = (Shopping) Proxy.newProxyInstance(Shopping.class.getClassLoader(),</span><br><span class="line">women.getClass().getInterfaces(), <span class="keyword">new</span> ShoppingHandler(women));</span><br><span class="line"></span><br><span class="line">System.out.println(Arrays.toString(women.doShopping(<span class="number">100</span>)));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>动态代理主要处理InvocationHandler和Proxy类</p>
<h3 id="代理Hook"><a href="#代理Hook" class="headerlink" title="代理Hook"></a>代理Hook</h3><p>代理Hook我们知道代理有比原始对象更强大的能力，比如飞到国外买东西，比如坑钱坑货；那么很自然，如果我们自己创建代理对象，然后把原始对象替换为我们的代理对象，那么就可以在这个代理对象为所欲为了；修改参数，替换返回值，我们称之为Hook。<br>下面我们Hook掉startActivity这个方法，使得每次调用这个方法之前输出一条日志；（当然，这个输入日志有点点弱，只是为了展示原理；只要你想，你想可以替换参数，拦截这个startActivity过程，使得调用它导致启动某个别的Activity，指鹿为马！）<br>首先我们得找到被Hook的对象，我称之为Hook点；什么样的对象比较好Hook呢？自然是容易找到的对象。什么样的对象容易找到？静态变量和单例；在一个进程之内，静态变量和单例变量是相对不容易发生变化的，因此非常容易定位，而普通的对象则要么无法标志，要么容易改变。我们根据这个原则找到所谓的Hook点。<br>然后我们分析一下startActivity的调用链，找出合适的Hook点。我们知道对于Context.startActivity（Activity.startActivity的调用链与之不同），由于Context的实现实际上是ContextImpl;我们看ConetxtImpl类的startActivity方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">startActivity</span><span class="params">(Intent intent, Bundle options)</span> </span>&#123;</span><br><span class="line">warnIfCallingFromSystemProcess();</span><br><span class="line"><span class="keyword">if</span> ((intent.getFlags()&amp;Intent.FLAG_ACTIVITY_NEW_TASK) == <span class="number">0</span>) &#123;</span><br><span class="line"><span class="keyword">throw</span> <span class="keyword">new</span> AndroidRuntimeException(</span><br><span class="line"><span class="string">"Calling startActivity() from outside of an Activity "</span></span><br><span class="line">+ <span class="string">" context requires the FLAG_ACTIVITY_NEW_TASK flag."</span></span><br><span class="line">+ <span class="string">" Is this really what you want?"</span>);</span><br><span class="line">&#125;</span><br><span class="line">mMainThread.getInstrumentation().execStartActivity(</span><br><span class="line">getOuterContext(), mMainThread.getApplicationThread(), <span class="keyword">null</span>,</span><br><span class="line">(Activity)<span class="keyword">null</span>, intent, -<span class="number">1</span>, options);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里，实际上使用了ActivityThread类的mInstrumentation成员的execStartActivity方法；注意到，ActivityThread 实际上是主线程，而主线程一个进程只有一个，因此这里是一个良好的Hook点。<br>接下来就是想要Hook掉我们的主线程对象，也就是把这个主线程对象里面的mInstrumentation给替换成我们修改过的代理对象；要替换主线程对象里面的字段，首先我们得拿到主线程对象的引用，如何获取呢？ActivityThread类里面有一个静态方法currentActivityThread可以帮助我们拿到这个对象类；但是ActivityThread是一个隐藏类，我们需要用反射去获取，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 先获取到当前的ActivityThread对象</span></span><br><span class="line">Class&lt;?&gt; activityThreadClass = Class.forName(<span class="string">"android.app.ActivityThread"</span>);</span><br><span class="line">Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod(<span class="string">"currentActivityThread"</span>);</span><br><span class="line">currentActivityThreadMethod.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">Object currentActivityThread = currentActivityThreadMethod.invoke(<span class="keyword">null</span>);</span><br></pre></td></tr></table></figure>

<p>拿到这个currentActivityThread之后，我们需要修改它的mInstrumentation这个字段为我们的代理对象，我们先实现这个代理对象，由于JDK动态代理只支持接口，而这个Instrumentation是一个类，没办法，我们只有手动写静态代理类，覆盖掉原始的方法即可。（cglib可以做到基于类的动态代理，这里先不介绍）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EvilInstrumentation</span> <span class="keyword">extends</span> <span class="title">Instrumentation</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String TAG = <span class="string">"EvilInstrumentation"</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// ActivityThread中原始的对象, 保存起来</span></span><br><span class="line">Instrumentation mBase;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">EvilInstrumentation</span><span class="params">(Instrumentation base)</span> </span>&#123;</span><br><span class="line">mBase = base;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> ActivityResult <span class="title">execStartActivity</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">Context who, IBinder contextThread, IBinder token, Activity target,</span></span></span><br><span class="line"><span class="function"><span class="params">Intent intent, <span class="keyword">int</span> requestCode, Bundle options)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Hook之前, XXX到此一游!</span></span><br><span class="line">Log.d(TAG, <span class="string">"\n执行了startActivity, 参数如下: \n"</span> + <span class="string">"who = ["</span> + who + <span class="string">"], "</span> +</span><br><span class="line"><span class="string">"\ncontextThread = ["</span> + contextThread + <span class="string">"], \ntoken = ["</span> + token + <span class="string">"], "</span> +</span><br><span class="line"><span class="string">"\ntarget = ["</span> + target + <span class="string">"], \nintent = ["</span> + intent +</span><br><span class="line"><span class="string">"], \nrequestCode = ["</span> + requestCode + <span class="string">"], \noptions = ["</span> + options + <span class="string">"]"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 开始调用原始的方法, 调不调用随你,但是不调用的话, 所有的startActivity都失效了.</span></span><br><span class="line"><span class="comment">// 由于这个方法是隐藏的,因此需要使用反射调用;首先找到这个方法</span></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">Method execStartActivity = Instrumentation.class.getDeclaredMethod(</span><br><span class="line"><span class="string">"execStartActivity"</span>,</span><br><span class="line">Context.class, IBinder.class, IBinder.class, Activity.class,</span><br><span class="line">Intent.class, <span class="keyword">int</span>.class, Bundle.class);</span><br><span class="line">execStartActivity.setAccessible(<span class="keyword">true</span>);</span><br><span class="line"><span class="keyword">return</span> (ActivityResult) execStartActivity.invoke(mBase, who,</span><br><span class="line">contextThread, token, target, intent, requestCode, options);</span><br><span class="line">&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line"><span class="comment">// 某该死的rom修改了 需要手动适配</span></span><br><span class="line"><span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"do not support!!! pls adapt it"</span>);</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Ok，有了代理对象，我们要做的就是偷梁换柱！代码比较简单，采用反射直接修改：</p>
<p>public static void attachContext() throws Exception{<br>// 先获取到当前的ActivityThread对象<br>Class&lt;?&gt; activityThreadClass = Class.forName(“android.app.ActivityThread”);<br>Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod(“currentActivityThread”);<br>currentActivityThreadMethod.setAccessible(true);<br>Object currentActivityThread = currentActivityThreadMethod.invoke(null);</p>
<p>// 拿到原始的 mInstrumentation字段<br>Field mInstrumentationField = activityThreadClass.getDeclaredField(“mInstrumentation”);<br>mInstrumentationField.setAccessible(true);<br>Instrumentation mInstrumentation = (Instrumentation) mInstrumentationField.get(currentActivityThread);</p>
<p>// 创建代理对象<br>Instrumentation evilInstrumentation = new EvilInstrumentation(mInstrumentation);</p>
<p>// 偷梁换柱<br>mInstrumentationField.set(currentActivityThread, evilInstrumentation);<br>}</p>
<p>好了，我们启动一个Activity测试一下，结果如下：<br><img src="https://img.vim-cn.com/00/f65b5679704e04d91cd2a48789c5d0aa7ed3b5.png" alt></p>
<p>可见，Hook确实成功了！这就是使用代理进行Hook的原理——偷梁换柱。整个Hook过程简要总结如下</p>

        </div>
        
          


  <section class='meta' id="footer-meta">
    <hr>
    <div class='new-meta-box'>
      
        
          <div class="new-meta-item date" itemprop="dateUpdated" datetime="2019-08-26T09:51:18+08:00">
  <a class='notlink'>
    <i class="fas fa-clock" aria-hidden="true"></i>
    <p>最后更新于 2019年8月26日</p>
  </a>
</div>

        
      
        
          
  
  <div class="new-meta-item meta-tags"><a class="tag" href="/tags/android快速开发/" rel="nofollow"><i class="fas fa-hashtag" aria-hidden="true"></i>&nbsp;<p>android快速开发</p></a></div> <div class="new-meta-item meta-tags"><a class="tag" href="/tags/hook/" rel="nofollow"><i class="fas fa-hashtag" aria-hidden="true"></i>&nbsp;<p>hook</p></a></div>


        
      
        
          
  <div class="new-meta-item share -mob-share-list">
  <div class="-mob-share-list share-body">
    
      
        <a class="-mob-share-qq" title="QQ好友" rel="external nofollow noopener noreferrer"
          
          href="http://connect.qq.com/widget/shareqq/index.html?url=https://zyqing.ml/2018/01/06/data/hookAndroid1/&title=Android插件化原理解析——Hook机制之动态代理 | 会飞的猪&summary=Android插件化使用代理机制进行API Hook进而达到方法增强是框架的常用手段，比如J2EE框架Spring通过动态代理优雅地实现了AOP编程，极大地提升了Web开发效率；同样，插件框架也广泛使用了代理机制来增强系统API从而达到插件化的目的。本文将带你了解基于动态代理的Hook机制。"
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/xaoxuu/assets@19.1.9/logo/128/qq.png">
          
        </a>
      
    
      
        <a class="-mob-share-qzone" title="QQ空间" rel="external nofollow noopener noreferrer"
          
          href="https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=https://zyqing.ml/2018/01/06/data/hookAndroid1/&title=Android插件化原理解析——Hook机制之动态代理 | 会飞的猪&summary=Android插件化使用代理机制进行API Hook进而达到方法增强是框架的常用手段，比如J2EE框架Spring通过动态代理优雅地实现了AOP编程，极大地提升了Web开发效率；同样，插件框架也广泛使用了代理机制来增强系统API从而达到插件化的目的。本文将带你了解基于动态代理的Hook机制。"
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/xaoxuu/assets@19.1.9/logo/128/qzone.png">
          
        </a>
      
    
      
        <a class="-mob-share-weibo" title="微博" rel="external nofollow noopener noreferrer"
          
          href="http://service.weibo.com/share/share.php?url=https://zyqing.ml/2018/01/06/data/hookAndroid1/&title=Android插件化原理解析——Hook机制之动态代理 | 会飞的猪&summary=Android插件化使用代理机制进行API Hook进而达到方法增强是框架的常用手段，比如J2EE框架Spring通过动态代理优雅地实现了AOP编程，极大地提升了Web开发效率；同样，插件框架也广泛使用了代理机制来增强系统API从而达到插件化的目的。本文将带你了解基于动态代理的Hook机制。"
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/xaoxuu/assets@19.1.9/logo/128/weibo.png">
          
        </a>
      
    
  </div>
</div>



        
      
    </div>
  </section>


        
        
            <div class="prev-next">
                
                    <section class="prev">
                        <span class="art-item-left">
                            <h6><i class="fas fa-chevron-left" aria-hidden="true"></i>&nbsp;上一页</h6>
                            <h4>
                                <a href="/2018/02/19/data/hookAndroid2/" rel="prev" title="Android 插件化原理解析——Activity生命周期管理">
                                  
                                      Android 插件化原理解析——Activity生命周期管理
                                  
                                </a>
                            </h4>
                            
                                
                                <h6 class="tags">
                                    <a class="tag" href="/tags/android快速开发/"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i>android快速开发</a> <a class="tag" href="/tags/hook/"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i>hook</a>
                                </h6>
                            
                        </span>
                    </section>
                
                
            </div>
        
      </section>
    </article>
  

  
    <!-- 显示推荐文章和评论 -->



  <article class="post white-box comments">
    <section class="article typo">
      <h4><i class="fas fa-comments fa-fw" aria-hidden="true"></i>&nbsp;评论</h4>
      
      
      
      
        <section id="comments">
          <div id="valine_container" class="valine_thread">
            <i class="fas fa-spinner fa-spin fa-fw"></i>
          </div>
        </section>
      
    </section>
  </article>


  




<!-- 根据页面mathjax变量决定是否加载MathJax数学公式js -->



  <script>
    window.subData = {
      title: 'Android插件化原理解析——Hook机制之动态代理',
      tools: true
    }
  </script>


</div>
<aside class='l_side'>
  
    
    
      
        
          
          
            <section class='widget author'>
  <div class='content material'>
    
      <div class='avatar'>
        <img class='avatar' src='http://zy_qing.gitee.io/resources/img/touxiang.jpg'/>
      </div>
    
     
      <div class='text'>
        
        
        
          <p><span id="jinrishici-sentence">柳暗花明又一村</span></p>
          <script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>
        
      </div>
    
    
      <div class="social-wrapper">
        
          
            <a href="mailto:1091425078@qq.com"
              class="social fas fa-envelope flat-btn"
              target="_blank"
              rel="external nofollow noopener noreferrer">
            </a>
          
        
          
            <a href="https://github.com/YongQingAndroid"
              class="social fab fa-github flat-btn"
              target="_blank"
              rel="external nofollow noopener noreferrer">
            </a>
          
        
          
            <a href="https://music.163.com/#/user/home?id=343100855"
              class="social fas fa-headphones-alt flat-btn"
              target="_blank"
              rel="external nofollow noopener noreferrer">
            </a>
          
        
      </div>
    
  </div>
</section>

          
        
      
        
          
          
            <section class='widget list'>
  
<header class='material'>
  <div><i class="fas fa-map-signs fa-fw" aria-hidden="true"></i>&nbsp;&nbsp;常用功能</div>
  
</header>

  <div class='content material'>
    <ul class="entry">
      
        <li><a class="flat-box" title="https://dev.tencent.com/u/zyqandroid/p/blog/git" href="https://dev.tencent.com/u/zyqandroid/p/blog/git"
          
          
          >
          <div class='name'>
            
              <i class="fas fa-clock fa-fw" aria-hidden="true"></i>
            
            &nbsp;&nbsp;我的GIT
          </div>
          
        </a></li>
      
        <li><a class="flat-box" title="/markPage/" href="/markPage/"
          
          
          >
          <div class='name'>
            
              <i class="fas fa-archive fa-fw" aria-hidden="true"></i>
            
            &nbsp;&nbsp;本地markDown工具
          </div>
          
        </a></li>
      
        <li><a class="flat-box" title="/2md/" href="/2md/"
          
          
          >
          <div class='name'>
            
              <i class="fas fa-book fa-fw" aria-hidden="true"></i>
            
            &nbsp;&nbsp;HTML转MD
          </div>
          
        </a></li>
      
        <li><a class="flat-box" title="http://zy_qing.gitee.io/resources/" href="http://zy_qing.gitee.io/resources/"
          
          
          >
          <div class='name'>
            
              <i class="fas fa-archive fa-fw" aria-hidden="true"></i>
            
            &nbsp;&nbsp;备用markDown工具
          </div>
          
        </a></li>
      
    </ul>
  </div>
</section>

          
        
      
        
          
          
            
  <section class='widget toc-wrapper'>
    
<header class='material'>
  <div><i class="fas fa-list fa-fw" aria-hidden="true"></i>&nbsp;&nbsp;本文目录</div>
  
    <div class='wrapper'><a class="s-toc rightBtn" rel="external nofollow noopener noreferrer" href="javascript:void(0)"><i class="fas fa-thumbtack fa-fw"></i></a></div>
  
</header>

    <div class='content material'>
      <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Android插件化"><span class="toc-text">Android插件化</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#代理是什么"><span class="toc-text">代理是什么</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#静态代理"><span class="toc-text">静态代理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#动态代理"><span class="toc-text">动态代理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#代理Hook"><span class="toc-text">代理Hook</span></a></li></ol></li></ol></li></ol>
    </div>
  </section>


          
        
      
        
          
          
            <section class='widget list'>
  
<header class='material'>
  <div><i class="fas fa-map-signs fa-fw" aria-hidden="true"></i>&nbsp;&nbsp;站内导航</div>
  
</header>

  <div class='content material'>
    <ul class="entry">
      
        <li><a class="flat-box" title="/" href="/"
          
          
          >
          <div class='name'>
            
              <i class="fas fa-clock fa-fw" aria-hidden="true"></i>
            
            &nbsp;&nbsp;近期文章
          </div>
          
        </a></li>
      
        <li><a class="flat-box" title="/blog/archives/" href="/blog/archives/"
          
            rel="nofollow"
          
          
          >
          <div class='name'>
            
              <i class="fas fa-archive fa-fw" aria-hidden="true"></i>
            
            &nbsp;&nbsp;文章归档
          </div>
          
        </a></li>
      
        <li><a class="flat-box" title="/projects/" href="/projects/"
          
          
          >
          <div class='name'>
            
              <i class="fas fa-code-branch fa-fw" aria-hidden="true"></i>
            
            &nbsp;&nbsp;开源项目
          </div>
          
        </a></li>
      
        <li><a class="flat-box" title="/friends/" href="/friends/"
          
            rel="nofollow"
          
          
          >
          <div class='name'>
            
              <i class="fas fa-link fa-fw" aria-hidden="true"></i>
            
            &nbsp;&nbsp;我的友链
          </div>
          
        </a></li>
      
        <li><a class="flat-box" title="/about/" href="/about/"
          
            rel="nofollow"
          
          
          >
          <div class='name'>
            
              <i class="fas fa-info-circle fa-fw" aria-hidden="true"></i>
            
            &nbsp;&nbsp;关于我
          </div>
          
        </a></li>
      
    </ul>
  </div>
</section>

          
        
      
        
          
          
            
  <section class='widget category'>
    
<header class='material'>
  <div><i class="fas fa-folder-open fa-fw" aria-hidden="true"></i>&nbsp;&nbsp;文章分类</div>
  
    <a class="rightBtn"
    
      rel="nofollow"
    
    
    href="/blog/categories/"
    title="blog/categories/">
    <i class="fas fa-expand-arrows-alt fa-fw"></i></a>
  
</header>

    <div class='content material'>
      <ul class="entry">
        
          <li><a class="flat-box" title="/categories/Android/" href="/categories/Android/"><div class='name'>Android</div><div class='badge'>(6)</div></a></li>
        
          <li><a class="flat-box" title="/categories/教程/" href="/categories/教程/"><div class='name'>教程</div><div class='badge'>(1)</div></a></li>
        
      </ul>
    </div>
  </section>


          
        
      
        
          
          
            
  <section class='widget tagcloud'>
    
<header class='material'>
  <div><i class="fas fa-fire fa-fw" aria-hidden="true"></i>&nbsp;&nbsp;热门标签</div>
  
    <a class="rightBtn"
    
      rel="nofollow"
    
    
    href="/blog/tags/"
    title="blog/tags/">
    <i class="fas fa-expand-arrows-alt fa-fw"></i></a>
  
</header>

    <div class='content material'>
      <a href="/tags/android/" style="font-size: 14px; color: #999">android</a> <a href="/tags/android快速开发/" style="font-size: 24px; color: #555">android快速开发</a> <a href="/tags/hook/" style="font-size: 19px; color: #777">hook</a> <a href="/tags/rxjava/" style="font-size: 14px; color: #999">rxjava</a> <a href="/tags/测试标签/" style="font-size: 19px; color: #777">测试标签</a>
    </div>
  </section>


          
        
      
        
          
          
            


  <section class='widget music'>
    
<header class='material'>
  <div><i class="fas fa-compact-disc fa-fw" aria-hidden="true"></i>&nbsp;&nbsp;最近在听</div>
  
    <a class="rightBtn"
    
      rel="external nofollow noopener noreferrer"
    
    
      target="_blank"
    
    href="https://music.163.com/#/user/home?id=343100855"
    title="https://music.163.com/#/user/home?id=343100855">
    <i class="far fa-heart fa-fw"></i></a>
  
</header>

    <div class='content material'>
      
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer@1.7.0/dist/APlayer.min.css">
  <div class="aplayer"
    data-theme="#1BCDFC"
    
    
    data-mode="circulation"
    data-server="netease"
    data-type="playlist"
    data-id="481100619"
    data-volume="0.7">
  </div>
  <script src="https://cdn.jsdelivr.net/npm/aplayer@1.7.0/dist/APlayer.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/meting@1.1.0/dist/Meting.min.js"></script>


    </div>
  </section>


          
        
      
    

  
</aside>

<footer id="footer" class="clearfix">
  
  
    <div class="social-wrapper">
      
        
          <a href="mailto:1091425078@qq.com"
            class="social fas fa-envelope flat-btn"
            target="_blank"
            rel="external nofollow noopener noreferrer">
          </a>
        
      
        
          <a href="https://github.com/YongQingAndroid"
            class="social fab fa-github flat-btn"
            target="_blank"
            rel="external nofollow noopener noreferrer">
          </a>
        
      
        
          <a href="https://music.163.com/#/user/home?id=343100855"
            class="social fas fa-headphones-alt flat-btn"
            target="_blank"
            rel="external nofollow noopener noreferrer">
          </a>
        
      
    </div>
  
  <br>
  <div><p>博客内容遵循 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议</a></p>
</div>
  <div>
    本站使用
    <a href="https://xaoxuu.com/wiki/material-x/" target="_blank" class="codename">Material X</a>
    作为主题
    
      ，
      总访问量为
      <span id="busuanzi_value_site_pv"><i class="fas fa-spinner fa-spin fa-fw" aria-hidden="true"></i></span>
      次
    
    。
  </div>
  <!-- 血小板 -->
  <div id="landlord">
      <div class="message" style="opacity:0"></div>
      <canvas id="live2d" width="560" height="500" class="live2d"></canvas>
      <div class="hide-button">隐藏</div>
  </div>
</footer>
<script>setLoadingBarProgress(80);</script>
<!-- live2d 血小板 -->
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
    var message_Path = '/live2d/'
    var home_Path = 'https://haremu.com/'
</script>
<script type="text/javascript" src="/live2d/js/live2d.js"></script>
<script type="text/javascript" src="/live2d/js/message.js"></script>
<script type="text/javascript">
    loadlive2d("live2d", "/live2d/model/xiaoban/model.json");
</script>


      <script>setLoadingBarProgress(60);</script>
    </div>
    <a class="s-top fas fa-arrow-up fa-fw" href='javascript:void(0)'></a>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>

  <script>
    var GOOGLE_CUSTOM_SEARCH_API_KEY = "";
    var GOOGLE_CUSTOM_SEARCH_ENGINE_ID = "";
    var ALGOLIA_API_KEY = "";
    var ALGOLIA_APP_ID = "";
    var ALGOLIA_INDEX_NAME = "";
    var AZURE_SERVICE_NAME = "";
    var AZURE_INDEX_NAME = "";
    var AZURE_QUERY_KEY = "";
    var BAIDU_API_ID = "";
    var SEARCH_SERVICE = "hexo" || "hexo";
    var ROOT = "/"||"/";
    if(!ROOT.endsWith('/'))ROOT += '/';
  </script>

<script src="//instant.page/1.2.2" type="module" integrity="sha384-2xV8M5griQmzyiY3CDqh1dn4z3llDVqZDqzjzcY+jCBCk/a5fXJmuZ/40JJAPeoU"></script>


  <script async src="https://cdn.jsdelivr.net/npm/scrollreveal@4.0.5/dist/scrollreveal.min.js"></script>
  <script type="text/javascript">
    $(function() {
      const $reveal = $('.reveal');
      if ($reveal.length === 0) return;
      const sr = ScrollReveal({ distance: 0 });
      sr.reveal('.reveal');
    });
  </script>


  <script src="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.js"></script>
  <script type="text/javascript">
    $(function() {
      Waves.attach('.flat-btn', ['waves-button']);
      Waves.attach('.float-btn', ['waves-button', 'waves-float']);
      Waves.attach('.float-btn-light', ['waves-button', 'waves-float', 'waves-light']);
      Waves.attach('.flat-box', ['waves-block']);
      Waves.attach('.float-box', ['waves-block', 'waves-float']);
      Waves.attach('.waves-image');
      Waves.init();
    });
  </script>


  <script async src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-busuanzi@2.3/js/busuanzi.pure.mini.js"></script>












  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
    
      <script src="https://cdn.jsdelivr.net/gh/xaoxuu/volantis@1.0/js/volantis.min.js"></script>
    
  
  <script>
  var GUEST_INFO = ['nick','mail','link'];
  var guest_info = 'nick,mail,link'.split(',').filter(function(item){
    return GUEST_INFO.indexOf(item) > -1
  });
  var notify = 'true' == true;
  var verify = 'true' == true;
  var valine = new Valine();
  valine.init({
    el: '#valine_container',
    notify: notify,
    verify: verify,
    guest_info: guest_info,
    
    appId: "nbvwRDSIj9302hYN0p3EgCgT-gzGzoHsz",
    appKey: "XVOUM8qKVsqegg2TnN7sHpMQ",
    placeholder: "快来评论吧~",
    pageSize:'10',
    avatar:'mp',
    lang:'zh-cn',
    highlight:'true'
  })
  </script>



  <script src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-material-x@19.5/js/app.js"></script>


  <script src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-material-x@19.5/js/search.js"></script>




<!-- 复制 -->
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  let COPY_SUCCESS = "复制成功";
  let COPY_FAILURE = "复制失败";
  /*页面载入完成后，创建复制按钮*/
  !function (e, t, a) {
    /* code */
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '  <i class="fa fa-copy"></i><span>复制</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });

      clipboard.on('success', function(e) {
        //您可以加入成功提示
        console.info('Action:', e.action);
        console.info('Text:', e.text);
        console.info('Trigger:', e.trigger);
        success_prompt(COPY_SUCCESS);
        e.clearSelection();
      });
      clipboard.on('error', function(e) {
        //您可以加入失败提示
        console.error('Action:', e.action);
        console.error('Trigger:', e.trigger);
        fail_prompt(COPY_FAILURE);
      });
    }
    initCopyCode();

  }(window, document);

  /**
   * 弹出式提示框，默认1.5秒自动消失
   * @param message 提示信息
   * @param style 提示样式，有alert-success、alert-danger、alert-warning、alert-info
   * @param time 消失时间
   */
  var prompt = function (message, style, time)
  {
      style = (style === undefined) ? 'alert-success' : style;
      time = (time === undefined) ? 1500 : time*1000;
      $('<div>')
          .appendTo('body')
          .addClass('alert ' + style)
          .html(message)
          .show()
          .delay(time)
          .fadeOut();
  };

  // 成功提示
  var success_prompt = function(message, time)
  {
      prompt(message, 'alert-success', time);
  };

  // 失败提示
  var fail_prompt = function(message, time)
  {
      prompt(message, 'alert-danger', time);
  };

  // 提醒
  var warning_prompt = function(message, time)
  {
      prompt(message, 'alert-warning', time);
  };

  // 信息提示
  var info_prompt = function(message, time)
  {
      prompt(message, 'alert-info', time);
  };

</script>


<!-- fancybox -->
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>
<script>
  let LAZY_LOAD_IMAGE = "";
  $(".article-entry").find("fancybox").find("img").each(function () {
      var element = document.createElement("a");
      $(element).attr("data-fancybox", "gallery");
      $(element).attr("href", $(this).attr("src"));
      /* 图片采用懒加载处理时,
       * 一般图片标签内会有个属性名来存放图片的真实地址，比如 data-original,
       * 那么此处将原本的属性名src替换为对应属性名data-original,
       * 修改如下
       */
       if (LAZY_LOAD_IMAGE) {
         $(element).attr("href", $(this).attr("data-original"));
       }
      $(this).wrap(element);
  });
</script>





  <script>setLoadingBarProgress(100);</script>

</body>
</html>
<!--单击显示文字-->
<script type="text/javascript" src="/js/click_show_text.js"></script>

